<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>工序流转统计</span>
        </div>
      </template>

      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px">
        <el-form-item label="产品" prop="productId">
          <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable>
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="工序效率统计" name="efficiency">
          <div class="chart-container">
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="chart-wrapper">
                  <div id="efficiencyChart" ref="efficiencyChart" style="width: 100%; height: 400px;"></div>
                </div>
              </el-col>
            </el-row>

            <el-divider />

            <el-table v-loading="loading" :data="efficiencyData" border>
              <el-table-column label="工序名称" align="center" prop="processName" />
              <el-table-column label="平均处理时间(小时)" align="center" prop="avgProcessTime" />
              <el-table-column label="最短时间(小时)" align="center" prop="minProcessTime" />
              <el-table-column label="最长时间(小时)" align="center" prop="maxProcessTime" />
              <el-table-column label="标准偏差" align="center" prop="stdDeviation" />
              <el-table-column label="处理批次数" align="center" prop="batchCount" />
              <el-table-column label="效率指数" align="center" prop="efficiencyIndex">
                <template #default="scope">
                  <el-progress
                    :percentage="scope.row.efficiencyIndex"
                    :color="getEfficiencyColor(scope.row.efficiencyIndex)"
                  ></el-progress>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="瓶颈工序分析" name="bottleneck">
          <div class="chart-container">
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="chart-wrapper">
                  <div id="bottleneckChart" ref="bottleneckChart" style="width: 100%; height: 400px;"></div>
                </div>
              </el-col>
            </el-row>

            <el-divider />

            <el-descriptions title="瓶颈工序分析" :column="1" border>
              <el-descriptions-item v-if="bottleneckReport.mainBottleneck" label="主要瓶颈工序">
                <el-tag type="danger">{{ bottleneckReport.mainBottleneck }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item v-if="bottleneckReport.secondaryBottleneck" label="次要瓶颈工序">
                <el-tag type="warning">{{ bottleneckReport.secondaryBottleneck }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="瓶颈分析">{{ bottleneckReport.analysis || '暂无分析数据' }}</el-descriptions-item>
              <el-descriptions-item label="改进建议">{{ bottleneckReport.recommendations || '暂无改进建议' }}</el-descriptions-item>
            </el-descriptions>

            <el-divider />

            <el-table v-loading="loading" :data="bottleneckData" border>
              <el-table-column label="工序名称" align="center" prop="processName" />
              <el-table-column label="平均等待时间(小时)" align="center" prop="avgWaitTime" />
              <el-table-column label="平均处理时间(小时)" align="center" prop="avgProcessTime" />
              <el-table-column label="异常发生率" align="center" prop="exceptionRate">
                <template #default="scope">
                  <el-tag :type="scope.row.exceptionRate > 10 ? 'danger' : (scope.row.exceptionRate > 5 ? 'warning' : 'success')">
                    {{ scope.row.exceptionRate }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="瓶颈指数" align="center" prop="bottleneckIndex">
                <template #default="scope">
                  <el-progress
                    :percentage="scope.row.bottleneckIndex"
                    :color="getBottleneckColor(scope.row.bottleneckIndex)"
                  ></el-progress>
                </template>
              </el-table-column>
              <el-table-column label="影响因素" align="center" prop="factors" :show-overflow-tooltip="true" />
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="生产周期分析" name="cycle">
          <div class="chart-container">
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="chart-wrapper">
                  <div id="cycleChart" ref="cycleChart" style="width: 100%; height: 400px;"></div>
                </div>
              </el-col>
            </el-row>

            <el-divider />

            <el-row :gutter="20">
              <el-col :span="8">
                <el-statistic title="平均生产周期(天)" :value="cycleReport.avgCycle" :precision="1">
                  <template #suffix>
                    <span>天</span>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="8">
                <el-statistic title="最短生产周期(天)" :value="cycleReport.minCycle" :precision="1">
                  <template #suffix>
                    <span>天</span>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="8">
                <el-statistic title="最长生产周期(天)" :value="cycleReport.maxCycle" :precision="1">
                  <template #suffix>
                    <span>天</span>
                  </template>
                </el-statistic>
              </el-col>
            </el-row>

            <el-divider />

            <el-table v-loading="loading" :data="cycleData" border>
              <el-table-column label="批次号" align="center" prop="batchCode" />
              <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
              <el-table-column label="开始日期" align="center" prop="startDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束日期" align="center" prop="endDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="生产周期(天)" align="center" prop="cycleDays" />
              <el-table-column label="计划周期(天)" align="center" prop="plannedCycleDays" />
              <el-table-column label="偏差(天)" align="center" prop="cycleDiff">
                <template #default="scope">
                  <el-tag :type="scope.row.cycleDiff > 0 ? 'danger' : 'success'">
                    {{ scope.row.cycleDiff > 0 ? '+' + scope.row.cycleDiff : scope.row.cycleDiff }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { parseTime } from '@/utils/ruoyi'
// 注释掉原有API导入
// import { getProcessEfficiency, getBottleneckAnalysis, getProductionCycleAnalysis } from '@/api/qep/production'
// import { listProduct } from '@/api/qep/product'
import * as echarts from 'echarts'
// 导入mock数据
import { processStatsMockData } from '@/mock/production'

// 遮罩层
const loading = ref(false)
// 选中标签
const activeName = ref('efficiency')
// 日期范围
const dateRange = ref([])
// 产品选项
const productOptions = ref([])
// 工序效率图表
let efficiencyChartInstance = null
// 瓶颈工序图表
let bottleneckChartInstance = null
// 周期分析图表
let cycleChartInstance = null
// 图表容器
const efficiencyChart = ref(null)
const bottleneckChart = ref(null)
const cycleChart = ref(null)
// 查询参数
const queryParams = reactive({
  productId: undefined,
  startDate: undefined,
  endDate: undefined
})

// 效率数据
const efficiencyData = ref([])
// 瓶颈数据
const bottleneckData = ref([])
// 周期数据
const cycleData = ref([])
// 瓶颈报告
const bottleneckReport = reactive({
  mainBottleneck: '',
  secondaryBottleneck: '',
  analysis: '',
  recommendations: ''
})
// 周期报告
const cycleReport = reactive({
  avgCycle: 0,
  minCycle: 0,
  maxCycle: 0
})

// 获取效率颜色
const getEfficiencyColor = (value) => {
  if (value < 40) return '#F56C6C'
  if (value < 70) return '#E6A23C'
  return '#67C23A'
}

// 获取瓶颈颜色
const getBottleneckColor = (value) => {
  if (value > 70) return '#F56C6C'
  if (value > 40) return '#E6A23C'
  return '#67C23A'
}

// 初始化图表
const initCharts = async () => {
  // 使用nextTick确保DOM已完全渲染
  await nextTick();
  
  // 延迟初始化图表，给DOM足够的时间渲染
  setTimeout(() => {
    // 销毁现有图表实例
    if (efficiencyChartInstance) {
      efficiencyChartInstance.dispose();
    }
    if (bottleneckChartInstance) {
      bottleneckChartInstance.dispose();
    }
    if (cycleChartInstance) {
      cycleChartInstance.dispose();
    }

    // 检查DOM元素是否存在并有尺寸
    if (efficiencyChart.value && efficiencyChart.value.offsetHeight > 0) {
      efficiencyChartInstance = echarts.init(efficiencyChart.value);
    }
    if (bottleneckChart.value && bottleneckChart.value.offsetHeight > 0) {
      bottleneckChartInstance = echarts.init(bottleneckChart.value);
    }
    if (cycleChart.value && cycleChart.value.offsetHeight > 0) {
      cycleChartInstance = echarts.init(cycleChart.value);
    }
    
    // 根据当前活动标签加载对应数据
    handleTabClick();
  }, 300);
}

// 渲染效率图表
const renderEfficiencyChart = (data) => {
  if (!efficiencyChartInstance) {
    if (efficiencyChart.value && efficiencyChart.value.offsetHeight > 0) {
      efficiencyChartInstance = echarts.init(efficiencyChart.value);
    } else {
      return;
    }
  }

  const processNames = data.map(item => item.processName)
  const avgProcessTimes = data.map(item => item.avgProcessTime)
  const efficiencyIndices = data.map(item => item.efficiencyIndex)

  const option = {
    title: {
      text: '工序效率统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['平均处理时间(小时)', '效率指数(%)'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: processNames,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '处理时间(小时)',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '效率指数(%)',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '平均处理时间(小时)',
        type: 'bar',
        barWidth: 20,
        data: avgProcessTimes
      },
      {
        name: '效率指数(%)',
        type: 'line',
        yAxisIndex: 1,
        data: efficiencyIndices,
        markLine: {
          data: [
            {
              name: '标准线',
              yAxis: 70
            }
          ]
        }
      }
    ]
  }

  efficiencyChartInstance.setOption(option)
}

// 渲染瓶颈图表
const renderBottleneckChart = (data) => {
  if (!bottleneckChartInstance) {
    if (bottleneckChart.value && bottleneckChart.value.offsetHeight > 0) {
      bottleneckChartInstance = echarts.init(bottleneckChart.value);
    } else {
      return;
    }
  }

  const processNames = data.map(item => item.processName)
  const avgWaitTimes = data.map(item => item.avgWaitTime)
  const avgProcessTimes = data.map(item => item.avgProcessTime)
  const bottleneckIndices = data.map(item => item.bottleneckIndex)

  const option = {
    title: {
      text: '瓶颈工序分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['平均等待时间(小时)', '平均处理时间(小时)', '瓶颈指数(%)'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: processNames,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '时间(小时)',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '瓶颈指数(%)',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '平均等待时间(小时)',
        type: 'bar',
        barWidth: 15,
        stack: 'total',
        data: avgWaitTimes
      },
      {
        name: '平均处理时间(小时)',
        type: 'bar',
        barWidth: 15,
        stack: 'total',
        data: avgProcessTimes
      },
      {
        name: '瓶颈指数(%)',
        type: 'line',
        yAxisIndex: 1,
        data: bottleneckIndices,
        markLine: {
          data: [
            {
              name: '警戒线',
              yAxis: 70,
              lineStyle: {
                color: '#F56C6C'
              }
            }
          ].filter(item => item.yAxis !== null && item.yAxis !== undefined && !isNaN(item.yAxis))
        }
      }
    ]
  }

  bottleneckChartInstance.setOption(option)
}

// 渲染周期图表
const renderCycleChart = (data) => {
  if (!cycleChartInstance) {
    if (cycleChart.value && cycleChart.value.offsetHeight > 0) {
      cycleChartInstance = echarts.init(cycleChart.value);
    } else {
      return;
    }
  }

  const batchCodes = data.map(item => item.batchCode)
  const cycleDays = data.map(item => item.cycleDays)
  const plannedCycleDays = data.map(item => item.plannedCycleDays)

  const option = {
    title: {
      text: '生产周期分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['实际周期(天)', '计划周期(天)'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: batchCodes,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '周期(天)',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '实际周期(天)',
        type: 'bar',
        barWidth: 20,
        data: cycleDays
      },
      {
        name: '计划周期(天)',
        type: 'line',
        data: plannedCycleDays,
        markLine: {
          data: [
            {
              name: '平均线',
              type: 'average'
            }
          ].filter(item => item.type === 'average' || (item.yAxis !== null && item.yAxis !== undefined && !isNaN(item.yAxis)))
        }
      }
    ]
  }

  cycleChartInstance.setOption(option)
}

// 使用mock数据获取产品列表
const getProductList = () => {
  productOptions.value = processStatsMockData.productOptions;
}

// 使用mock数据获取效率数据
const getEfficiencyData = () => {
  loading.value = true;
  
  // 模拟API调用延迟
  setTimeout(() => {
    efficiencyData.value = processStatsMockData.efficiencyData;
    renderEfficiencyChart(efficiencyData.value);
    loading.value = false;
  }, 500);
}

// 使用mock数据获取瓶颈分析数据
const getBottleneckData = () => {
  loading.value = true;
  
  // 模拟API调用延迟
  setTimeout(() => {
    bottleneckData.value = processStatsMockData.bottleneckData;
    Object.assign(bottleneckReport, processStatsMockData.bottleneckReport);
    renderBottleneckChart(bottleneckData.value);
    loading.value = false;
  }, 500);
}

// 使用mock数据获取生产周期分析数据
const getCycleData = () => {
  loading.value = true;
  
  // 模拟API调用延迟
  setTimeout(() => {
    cycleData.value = processStatsMockData.cycleData;
    Object.assign(cycleReport, processStatsMockData.cycleReport);
    renderCycleChart(cycleData.value);
    loading.value = false;
  }, 500);
}

// 处理标签点击
const handleTabClick = () => {
  if (activeName.value === 'efficiency') {
    getEfficiencyData();
  } else if (activeName.value === 'bottleneck') {
    getBottleneckData();
  } else if (activeName.value === 'cycle') {
    getCycleData();
  }
}

// 搜索按钮操作
const handleQuery = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.startDate = dateRange.value[0]
    queryParams.endDate = dateRange.value[1]
  } else {
    queryParams.startDate = undefined
    queryParams.endDate = undefined
  }
  
  // 根据当前活动标签重新加载数据
  handleTabClick();
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryParams.productId = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  
  // 重新加载数据
  handleTabClick();
}

// 监听窗口大小变化，重新调整图表大小
const resizeHandler = () => {
  if (efficiencyChartInstance) {
    efficiencyChartInstance.resize()
  }
  if (bottleneckChartInstance) {
    bottleneckChartInstance.resize()
  }
  if (cycleChartInstance) {
    cycleChartInstance.resize()
  }
}

onMounted(() => {
  // 获取产品列表
  getProductList();
  
  // 初始化图表
  initCharts();
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', resizeHandler);
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeHandler);
  
  // 销毁图表实例
  if (efficiencyChartInstance) {
    efficiencyChartInstance.dispose();
    efficiencyChartInstance = null;
  }
  if (bottleneckChartInstance) {
    bottleneckChartInstance.dispose();
    bottleneckChartInstance = null;
  }
  if (cycleChartInstance) {
    cycleChartInstance.dispose();
    cycleChartInstance = null;
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  position: relative;
  padding: 20px;
  width: 100%;
  height: 100%;
}

.chart-wrapper {
  margin-bottom: 20px;
  height: 400px; /* 确保图表容器有固定高度 */
}

.el-divider {
  margin: 20px 0;
}
</style> 